﻿using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using WebApiAttributeDemo.Entities;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
using WebApiAttributeDemoClient;

namespace VSMWebApiClientDemo
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private ObservableCollection<BlogPost> _blogPosts;
        private BlogPost _currentPost;
        private BlogServiceClient _serviceClient;

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _serviceClient = new BlogServiceClient("http://localhost:49499/api/blog/");
            _currentPost = new BlogPost();
            Posts.DataContext = _blogPosts;
            CurrentPost.DataContext = _currentPost;
        }

        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            if (_currentPost.Id == 0)
            {
                await _serviceClient.CreatePost(_currentPost);
                _blogPosts = await _serviceClient.GetAllBlogs();
                Posts.DataContext = _blogPosts;
            }
            else
            {
                await _serviceClient.UpdatePost(_currentPost);
            }

            Posts.SelectedIndex = -1;
        }

        private void Posts_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                _currentPost = e.AddedItems[0] as BlogPost;
            }
            else if (e.RemovedItems.Count > 0)
            {
                _currentPost = new BlogPost();
            }
           
            CurrentPost.DataContext = _currentPost;
        }

        private async void Fetch_Click(object sender, RoutedEventArgs e)
        {
            Posts.DataContext =  await _serviceClient.FilterPosts(Filter.Text);
        }

        private async void Delete_Click(object sender, RoutedEventArgs e)
        {
            await _serviceClient.DeletePost(_currentPost);
            _blogPosts.Remove(_currentPost);
            _currentPost = new BlogPost();
        }
    }
}


    